<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>新增巡检配置</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="cancel">返回</el-button>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建人" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入创建人" disabled />
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="typeId">
              <el-select v-model="form.typeId" placeholder="请选择设备类型" style="width: 100%;">
                <el-option
                  v-for="item in equipmentTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
        </el-form-item>
          </el-col>
        </el-row>
        
        <el-row>
          <el-col :span="12">
            <el-form-item label="配置名称" prop="configName">
              <el-input v-model="form.configName" placeholder="请输入配置名称" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配置编码" prop="configCode">
              <el-input v-model="form.configCode" placeholder="请输入配置编码" />
        </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="负责部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择负责部门" @change="handleDeptChange">
                <el-option
                  v-for="item in deptOptions"
                  :key="item.deptId"
                  :label="item.deptName"
                  :value="item.deptId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配置类别" prop="configCategory">
              <el-radio-group v-model="form.configCategory">
                <el-radio label="0">标准配置</el-radio>
                <el-radio label="1">自定义配置</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="配置说明" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入配置说明" />
        </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">巡检项管理</el-divider>
        
        <el-row>
          <el-col :span="24" style="text-align: right; margin-bottom: 20px;">
            <el-button type="primary" @click="handleAddItem">新增巡检项</el-button>
          </el-col>
        </el-row>

        <el-table :data="itemList" border style="width: 100%">
          <el-table-column type="index" width="50" label="序号" />
          <el-table-column prop="itemName" label="巡检项名称" min-width="120" />
          <el-table-column prop="itemStandard" label="巡检标准" min-width="180" show-overflow-tooltip />
          <el-table-column prop="requireImage" label="图片必传" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.requireImage === '1' ? 'success' : 'info'">
                {{ scope.row.requireImage === '1' ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditItem(scope.row)">编辑</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteItem(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-form-item style="margin-top: 30px;">
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 巡检项新增/编辑弹窗 -->
    <el-dialog :title="itemDialog.title" :visible.sync="itemDialog.visible" width="500px" append-to-body>
      <el-form ref="itemForm" :model="itemForm" :rules="itemRules" label-width="100px">
        <el-form-item label="巡检项名称" prop="itemName">
          <el-input v-model="itemForm.itemName" placeholder="请输入巡检项名称" />
        </el-form-item>
        <el-form-item label="巡检标准" prop="itemStandard">
          <el-input v-model="itemForm.itemStandard" type="textarea" :rows="3" placeholder="请输入巡检标准" />
        </el-form-item>
        <el-form-item label="图片必传" prop="requireImage">
          <el-switch v-model="itemForm.requireImage" active-value="1" inactive-value="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="itemDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitItemForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addInspectionConfig } from '@/api/sb/inspectionConfig'
import { getTreeselect } from '@/api/sb/equipmentType'

export default {
  name: 'AddInspectionConfig',
  data() {
    return {
      // 表单参数
      form: {
        configName: '',
        configCode: '',
        typeId: null,
        createBy: this.$store.getters.name,
        remark: '',
        deptId: null, // 新增负责部门ID
        deptName: '', // 新增负责部门名称
        configCategory: '0' // 新增配置类别
      },
      // 巡检项列表
      itemList: [],
      // 设备类型树选项
      typeOptions: [],
      // 负责部门树选项
      deptOptions: [],
      // 表单校验
      rules: {
        createBy: [
          { required: true, message: '创建人不能为空', trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ],
        configName: [
          { required: true, message: '配置名称不能为空', trigger: 'blur' }
        ]
      },
      // 巡检项弹窗
      itemDialog: {
        visible: false,
        title: '新增巡检项',
        index: -1
      },
      // 巡检项表单
      itemForm: {
        itemName: '',
        itemStandard: '',
        requireImage: '0'
      },
      // 巡检项表单校验
      itemRules: {
        itemName: [
          { required: true, message: '巡检项名称不能为空', trigger: 'blur' }
        ],
        itemStandard: [
          { required: true, message: '巡检标准不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getTypeTree()
    this.getDeptTree() // 获取负责部门树
  },
  methods: {
    /** 获取设备类型树 */
    getTypeTree() {
      getTreeselect().then(response => {
        this.typeOptions = response.data
      })
    },
    /** 获取负责部门树 */
    getDeptTree() {
      this.$api.sb.dept.treeselect().then(response => {
        this.deptOptions = response.data
      })
    },
    /** 负责部门选择变化 */
    handleDeptChange(value) {
      const dept = this.deptOptions.find(item => item.deptId === value)
      if (dept) {
        this.form.deptName = dept.deptName
      }
    },
    /** 新增巡检项按钮操作 */
    handleAddItem() {
      this.itemDialog.title = '新增巡检项'
      this.itemDialog.index = -1
      this.resetItemForm()
      this.itemDialog.visible = true
    },
    /** 编辑巡检项按钮操作 */
    handleEditItem(row) {
      this.itemDialog.title = '编辑巡检项'
      this.itemDialog.index = this.itemList.indexOf(row)
      this.itemForm = JSON.parse(JSON.stringify(row))
      this.itemDialog.visible = true
    },
    /** 删除巡检项按钮操作 */
    handleDeleteItem(index) {
      this.$modal.confirm('是否确认删除该巡检项？').then(() => {
        this.itemList.splice(index, 1)
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 提交巡检项表单 */
    submitItemForm() {
      this.$refs.itemForm.validate(valid => {
        if (valid) {
          const item = JSON.parse(JSON.stringify(this.itemForm))
          if (this.itemDialog.index === -1) {
            // 新增
            this.itemList.push(item)
          } else {
            // 修改
            this.itemList.splice(this.itemDialog.index, 1, item)
          }
          this.itemDialog.visible = false
          this.$modal.msgSuccess('操作成功')
        }
      })
    },
    /** 重置巡检项表单 */
    resetItemForm() {
      this.itemForm = {
        itemName: '',
        itemStandard: '',
        requireImage: '0'
      }
      this.$nextTick(() => {
        this.$refs.itemForm && this.$refs.itemForm.resetFields()
      })
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.itemList.length === 0) {
            this.$modal.msgError('请至少添加一个巡检项')
            return
          }
          
          const data = {
            ...this.form,
            items: this.itemList
          }
          
          addInspectionConfig(data).then(response => {
            this.$modal.msgSuccess('新增成功')
            this.$router.push('/sb/inspection-config')
          })
        }
      })
    },
    /** 取消按钮 */
    cancel() {
      this.$router.push('/sb/inspection-config')
    }
  }
}
</script> 